#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: ystlong
# @Date:   2018-11-10 11:12:45
# @Last Modified by:   ystlong
# @Last Modified time: 2018-11-10 12:18:59

import sys
import os
import json
import urllib2
import urllib

cur_dir = os.path.dirname(__file__)
sys.path.append(os.path.join(cur_dir, "aliyun-openapi-python-sdk/aliyun-python-sdk-core"))
sys.path.append(os.path.join(cur_dir, "aliyun-openapi-python-sdk/aliyun-python-sdk-alidns"))

from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.acs_exception.exceptions import ClientException
from aliyunsdkcore.acs_exception.exceptions import ServerException
from aliyunsdkalidns.request.v20150109.DescribeDomainsRequest import DescribeDomainsRequest
from aliyunsdkalidns.request.v20150109.DescribeDomainRecordsRequest import DescribeDomainRecordsRequest
from aliyunsdkalidns.request.v20150109.UpdateDomainRecordRequest import UpdateDomainRecordRequest


# api 描述文档
# https://help.aliyun.com/document_detail/29739.html?spm=a2c4g.11174283.6.610.4bc34c02kIWbvn

def http_conn(url, params=None, GET=True):
    data = None
    request = None
    if params != None:
        data = urllib.urlencode(params)
    if GET == True:
        if data != None:
            url = url + "?" + data
        request = urllib2.Request(url)
    else:
        request = urllib2.Request(url, data)

    ret = urllib2.urlopen(request)

    if ret.getcode() < 200 or ret.getcode() >= 300:
        raise Exception("http request not success, code: %d"%(ret.getcode()))
    return ret.read()

def get_net_ip():
	url = "https://www.koyst.com/ip.php"
	r = http_conn(url)
	r = json.loads(r)
	return r["ip"]

# rr name maybe is uniqe
def get_recorde_by_rr(client, rr_name):
	request = DescribeDomainRecordsRequest()
	request.set_DomainName("koyst.com")
	request.set_RRKeyWord("nas")
	# 发起 API 请求
	response = client.do_action_with_exception(request)
	recored = json.loads(response)
	return recored

def set_recorde_a_rr(client, recored_id, rr_name, recored_ip):
	request = UpdateDomainRecordRequest()
	request.set_RecordId(recored_id)
	request.set_RR(rr_name)
	request.set_Type("A")
	request.set_Value(recored_ip)
	response = client.do_action_with_exception(request)
	ret = json.loads(response)
	print ret

def update_a_recored(client, rr_name="nas"):
	ip = get_net_ip()
	ret = get_recorde_by_rr(client, "nas")
	recored_item = ret["DomainRecords"]["Record"][0]
	recored_id = recored_item["RecordId"]
	current_ip = recored_item["Value"]
	if current_ip == ip:
		return
	set_recorde_a_rr(client, recored_id, "nas", ip)

def main():
	if len(sys.argv) != 3:
		print "usage: %s AccessKeyID AccessKeySecret"
		sys.exit(1)
	key_id = sys.argv[1]
	key_secret = sys.argv[2]
	region_id = "cn-shanghai"
	client = AcsClient(key_id, key_secret, region_id)
	update_a_recored(client, "nas")

if __name__ == '__main__':
	main()

